"""
Case Type   : 资源池化故障模式库
Case Name   : 套接字文件被修改-数据库运行时，修改套接字文件内容
Create At   : 2025/05
Owner       : haomeng
Description :
    1、查看集群状态
    2、运行tpcc业务
    3、查看套接字文件，修改套接字文件内容
    4、查看业务运行情况
    5、gsql方式直连数据库执行sql语句
    6、重启集群
    7、查看集群状态，查看套接字文件
Expect      :
    1、集群状态正常
    2、运行业务成功
    3、套接字文件存在
    4、业务运行正常无影响
    5、直连数据库执行sql语句成功
    6、重启集群成功
    6、集群状态正常,产生新的套接字文件
History     :
"""

import os
import time
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.ComThread import ComThread
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

class SSFauleMode(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.user_node = [Node(node='PrimaryRoot'), Node(node='PrimaryDbUser')]
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.com = Common()
        self.constant = Constant()
        self.socket_param = 'unix_socket_directory'

    def test_ss_faule(self):
        text = '-----step1:查看集群状态;  expect:集群状态正常-----'
        self.log.info(text)

        status = self.pri_sh.exec_cm_ctl('query', '-Cv')
        self.log.info(status)
        self.assertIn('Normal', status, '集群状态异常')

        text = '-----step2:执行tpcc读写业务  expect:业务执行成功-----'
        self.log.info(text)

        tpcc_cmd = f'./runBenchmark.sh {macro.PROPS_FILENAME}'
        self.log.info(tpcc_cmd)

        tpcc_execute = ComThread(self.com.start_tpcc, args=(self.user_node[0],
                                                               f'{macro.TPCC_PATH}',
                                                               tpcc_cmd))
        tpcc_execute.setDaemon(True)
        tpcc_execute.start()

        text = '-----step3:查看主节点套接字文件  expect:文件存在-----'
        self.log.info(text)

        socket_dir = self.com.show_param(self.socket_param)
        self.log.info(socket_dir)
        self.assertIn('mppdb', socket_dir, '获取套接字文件路径失败')

        get_file_list = self.user_node[1].sh(f'ls -al {socket_dir};').result()
        self.log.info(get_file_list)
        socket_file_name = ''
        for file in get_file_list.split():
            self.log.info(file)
            if (self.user_node[1].db_port not in file) or ('lock' in file):
                pass
            else:
                socket_file_name = file

        socket_file = os.path.join(socket_dir, socket_file_name)
        modify = f"echo 'test_pgsql' >> {socket_file}.lock;" \
                 f"cat {socket_file}.lock | grep 'test_pgsql';"
        self.log.info(modify)

        modify_execute = ComThread(self.com.get_sh_result, args=(self.user_node[1], modify))
        modify_execute.setDaemon(True)
        modify_execute.start()

        text = '-----step4:查看业务运行情况  expect:业务运行正常无影响-----'
        self.log.info(text)

        tpcc_execute.join(10 * 60)
        ret1 = tpcc_execute.get_result()
        self.log.info(ret1)
        self.assertIn('Session End', ret1, 'tpcc执行失败')

        modify_execute.join(10 * 60)
        ret2 = modify_execute.get_result()
        self.log.info(ret2)
        self.assertIn('test_pgsql', ret2, '套接字文件新增内容不存在')

        text = '-----step5:gsql方式直连数据库执行sql语句  expect:直连数据库执行sql语句失败-----'
        self.log.info(text)

        sql_res = self.user_node[1].sh(f'source {macro.DB_ENV_PATH};'
                                       f'gsql -d {self.user_node[1].db_name} '
                                       f'-p {self.user_node[1].db_port} '
                                       f'-c "select 1;"').result()
        self.log.info(sql_res)
        self.assertIn('1', sql_res.splitlines()[-2].strip(), '连接数据库失败')

        text = '-----step6:重启集群  expect:重启成功-----'
        self.log.info(text)

        restart = self.pri_sh.exec_cm_ctl('stop;', 'cm_ctl start')
        self.log.info(restart)
        self.assertIn(self.constant.cm_stop_success_msg, restart, '集群重启失败')
        self.assertIn(self.constant.cm_start_success_msg, restart, '集群重启失败')

        text = '-----step7:查看集群状态，查看套接字文件是否存在  ' \
               'expect:集群状态正常，产生新的套接字文件-----'
        self.log.info(text)

        status = self.pri_sh.exec_cm_ctl('query', '-Cv')
        self.log.info(status)
        self.assertIn('cluster_state   : Normal', status, '集群重启失败')

        check = f'ls -al {socket_file}.lock;cat {socket_file}.lock;'
        self.log.info(check)
        res = self.user_node[1].sh(check).result()
        self.log.info(res)
        self.assertIn(socket_file_name, res, '套接字文件不存在')
        self.assertNotIn('test_pgsql', res, '套接字文件新增内容存在,未产生新的套接字文件')

    def tearDown(self):
        self.log.info('-----No need to clean-----')
        self.log.info(f'----{os.path.basename(__file__)} end----')
